package com.king.zxing.app.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.hmsscankit.WriterException;
import com.huawei.hms.ml.scan.HmsBuildBitmapOption;
import com.huawei.hms.ml.scan.HmsScan;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@SuppressLint("Registered")
public class GenerateQrCodeUtil {
    private ImageView image;
    private static boolean isSuccess;
    private static boolean flag = false;
    /**
     * 生成并保存二维码
     */
    public static void generateQrcode(Context context,String strname, String str){
            //设置二维码名称
            if (strname.length() <= 0) {
                Toast.makeText(context, "请先输入控件名称！", Toast.LENGTH_SHORT).show();
                return;
            }
            //设置二维码内容.
            if (str.length() <= 0) {
                Toast.makeText(context, "请先输入内容！", Toast.LENGTH_SHORT).show();
                return;
            }
            //设置起始符号
            str ="start" + str + "@"+strname+"finish";
            try {
                //生成二维码.
                HmsBuildBitmapOption option = new HmsBuildBitmapOption.Creator().setBitmapMargin(1).setBitmapColor(Color.BLACK).setBitmapBackgroundColor(Color.WHITE).create();
                for (int n = 0; n <= (int) Math.floor(str.length() / 500); n++) {
                    String content1;
//                    if (n < (int) Math.floor(str.length() / 500)) {
                    if (n < (int) Math.floor(str.length() / 500) && str.substring(n*500).length() > 516) {
                        content1 = str.substring(n * 500, 500 * (n + 1));
                    } else {
                        content1 = str.substring(n * 500);
                    }
                    Bitmap resultImage = ScanUtil.buildBitmap(content1, HmsScan.QRCODE_SCAN_TYPE, 700, 700, option);//生成二维码

                    /*
                    保存二维码
                    */
                    try {
                        String fileName = strname + n + ".jpg";
                        String storePath = "/sdcard/Storagefactory/QR";
                        File file1=new File(storePath);
                        if (!file1.exists()) {
                            file1.mkdirs();
                        }
                        File[] files=file1.listFiles();
                        if (files == null){
//                            Log.e("error","空目录");
                            Toast.makeText(context, "未找到存储路径！", Toast.LENGTH_SHORT).show();
                        }
                        List<String> s = new ArrayList<>();
                        for(int i =0;i<files.length;i++){

                            s.add(files[i].getName());
                        }
                        for (int i = 0; i < s.size(); i++) {
                            if ((strname + n + ".jpg").equals(s.get(i))){
                                Toast.makeText(context, "已存在该控件！", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        }
                        File appDir = new File(storePath);
                        if (!appDir.exists()) {
                            appDir.mkdir();
                        }
                        File file = new File(appDir, fileName);
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        isSuccess = resultImage.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream);
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        Uri uri = Uri.fromFile(file);
                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                    } catch (Exception e) {
                        Log.w("GenerateQrCodeUtil", Objects.requireNonNull(e.getMessage()));
                        Toast.makeText(context, "未知错误", Toast.LENGTH_SHORT).show();
                    }
                }
                if (isSuccess) {
                    Toast.makeText(context, "二维码已保存在本地", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(context, "二维码保存失败", Toast.LENGTH_SHORT).show();
                }
            } catch (WriterException e) {
                Toast.makeText(context, "参数错误！", Toast.LENGTH_SHORT).show();
            }

    }
    /**
     * 显示生成的二维码
     */
    public static void showQrCode(final Context context, String strname, final ImageView image){
        final int[] count = {0};
        final Toast[] mtoast = new Toast[1];
        if (flag){
            Toast.makeText(context, "程序正在运行，请稍后再试！", Toast.LENGTH_SHORT).show();
            return;
        }
        if(strname.length()<=0){
            Toast.makeText(context, "请先输入控件名称！", Toast.LENGTH_SHORT).show();
            return;
        }
        String st;
        File file=new File("/sdcard/Storagefactory/QR/");
        if (!file.exists()){
            Toast.makeText(context, "不存在该目录！", Toast.LENGTH_SHORT).show();
            return;
        }
        File[] files=file.listFiles();
        if (files == null){
            Log.e("error","空目录");
        }
        List<String> s = new ArrayList<>();
        for(int i =0;i<files.length;i++){
            s.add(files[i].getName());
        }
        /*
        获取符合条件的Bitmap存入Bitmap数组中
         */
        boolean flag1 = true;
        int counter = 0;
        final Bitmap[] bm = new Bitmap[600];
        for (int i = 0; i < s.size(); i++) {
            for (int n = 0; n< s.size(); n++) {
                if ((strname + n + ".jpg").equals(s.get(i))){
                    flag1 = false;
                    st = "/sdcard/Storagefactory/QR/"+ s.get(i);
                    Uri uri = Uri.fromFile(new File(st));
                    try {
                        bm [counter] = MediaStore.Images.Media.getBitmap(context.getContentResolver(),uri);
                        counter++;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (flag1){
            Toast.makeText(context, "查询不到该控件，请检查控件名是否正确！", Toast.LENGTH_SHORT).show();
            return;
        }
        //显示该控件所有二维码
        final int finalCounter = counter;
        @SuppressLint("HandlerLeak") final Handler handler = new Handler() {
            public void handleMessage(android.os.Message msg) {

                if (msg.what == 0) {

                    image.setImageBitmap(bm[count[0]++]);
//                    System.out.println("第"+count+"张图片");
                    if (count[0] < finalCounter) {
                        mtoast[0] = null;
                        mtoast[0] = Toast.makeText(context, "这是第" + (count[0]) + "张图片 ！", Toast.LENGTH_SHORT);
                        mtoast[0].show();
                    }
                    if (count[0] >= finalCounter) {
//                        System.out.println("执行完一轮了！");
                        mtoast[0] = null;
                        mtoast[0] = Toast.makeText(context, "这是第最后一张图片 ！", Toast.LENGTH_LONG);
                        mtoast[0].show();
                        count[0] = 0;
                        flag =false;
                    }
                }
            }
        };
        flag = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    handler.sendEmptyMessage(0);
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    /**
     * 结束Handler
     */
    public static void closeHandler(){
        flag = false;
    }


}
